import { provide, inject, ref } from 'vue'
import { TypePageFocusState, TypeInjectPage, TypeKeyDownFn, TypePopupItem } from "../type";
import { keysIptv, keysOther } from "../path/key"
import { getKeyValue } from '../path/until';
import _ from "lodash"
class Store {
  constructor() {

  }
  provide() {
    const popupList = ref<TypePopupItem[]>([])
    const _focusState: TypePageFocusState = {
      keys: keysOther,
      popupList,
      keyDownStore: {},
    }
    provide('focus-store', _focusState)
    return {
      state: _focusState,
      changekeyValue: (ev: KeyboardEvent) => {
        const _keyValue = getKeyValue(ev.keyCode, _focusState.keys)
        if (!_keyValue) return
        for (const key in _focusState.keyDownStore) {
          if (Object.prototype.hasOwnProperty.call(_focusState.keyDownStore, key)) {
            const _fun = _focusState.keyDownStore[key];
            if (typeof _fun === "function") {
              _fun(_keyValue, ev)
            }
          }
        }
      },
    }
  }
  inject(): TypeInjectPage {
    const _focusState: TypePageFocusState = inject('focus-store', {
      keys: keysOther,
      popupList: ref<TypePopupItem[]>([]),
      keyDownStore: {},
    })
    return {
      state: _focusState,
      listenerKeyDown: (ev, fn) => this.listenerKeyDown(ev, fn, _focusState.keyDownStore),
      unListenerKeyDown: (ev) => this.unListenerKeyDown(ev, _focusState.keyDownStore),
    }
  }
  initKeys(state: TypePageFocusState, _isIptv: boolean) {
    state.keys = _isIptv ? keysIptv : keysOther
  }
  private listenerKeyDown(id: string, fn: TypeKeyDownFn, funs: { [key: string]: TypeKeyDownFn }) {
    if (typeof fn !== "function") throw new Error("请传入回调函数")
    funs[id] = fn
  }
  private unListenerKeyDown(id: string, funs: { [key: string]: TypeKeyDownFn }) {
    delete funs[id]
  }
}
export default new Store()